"use client"

import { Form, Input, Button, Space, Select } from "antd"
import { useHosts } from "../contexts/HostsContext"
import "./HostsBlockForm.scss"

const { TextArea } = Input
const { Option } = Select

interface HostsBlockFormProps {
  initialValues?: {
    name: string
    content: string
    description?: string
    environment?: string
  }
  onSubmit: (values: any) => void
  onCancel: () => void
}

const HostsBlockForm = ({ initialValues, onSubmit, onCancel }: HostsBlockFormProps) => {
  const [form] = Form.useForm()
  const { hostTypes } = useHosts()

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      onSubmit(values)
      form.resetFields()
    } catch (error) {
      console.error("Validation failed:", error)
    }
  }

  // Get environment types from hostTypes
  const environmentTypes = hostTypes.map((type) => type.name)

  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={
        initialValues || {
          environment: environmentTypes[0],
        }
      }
      className="hosts-block-form"
    >
      <Form.Item name="name" label="配置名称" rules={[{ required: true, message: "请输入配置名称" }]}>
        <Input placeholder="请输入配置名称" className="form-input" />
      </Form.Item>

      <Form.Item name="environment" label="类型" rules={[{ required: true, message: "请选择类型" }]}>
        <Select placeholder="请选择类型" className="form-select">
          {environmentTypes.map((type) => (
            <Option key={type} value={type}>
              {type}
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        name="content"
        label="Hosts 内容"
        rules={[{ required: true, message: "请输入 Hosts 内容" }]}
        extra="每行一条记录，支持注释（以 # 开头）"
      >
        <TextArea
          rows={10}
          placeholder={`# 加盟 测试 host
172.172.178.9 test.hzwjx.cn
172.172.178.9 hzwjx.cn
# 172.172.178.9 test.hzwjxweb.cn
172.172.178.93  www.hzwjx.cn
172.172.178.10  st.haiziwang.com
172.172.178.9 test.verifycode.haiziwang.com`}
          className="form-textarea"
          style={{ fontFamily: "monospace" }}
        />
      </Form.Item>

      <Form.Item name="description" label="描述">
        <TextArea rows={3} placeholder="请输入配置描述" className="form-textarea" />
      </Form.Item>

      <Form.Item className="form-actions">
        <Space>
          <Button type="primary" onClick={handleSubmit} className="form-button">
            {initialValues ? "更新" : "添加"}
          </Button>
          <Button onClick={onCancel} className="form-button">
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  )
}

export default HostsBlockForm
